package com.antdesignbackend.backend.controller;

import com.antdesignbackend.backend.aop.AuthToken;
import com.antdesignbackend.backend.common.returnResult.ReturnCode;
import com.antdesignbackend.backend.common.returnResult.ReturnVO;
import com.antdesignbackend.backend.entity.Button;
import com.antdesignbackend.backend.entity.Roles;
import com.antdesignbackend.backend.entity.entityVo.RolesVo;
import com.antdesignbackend.backend.service.PermissionService;
import com.antdesignbackend.backend.service.RolesService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

@Controller
@RequestMapping("/RoleManage")
public class RoleController {
    @Autowired
    RolesService rolesService;
    @Autowired
    PermissionService permissionService;

    private Logger logger = LoggerFactory.getLogger(this.getClass());
    private Integer menuId;

    @GetMapping("/index")
    @AuthToken
    public String roleIndex(String menuId) {
        this.menuId = Integer.parseInt(menuId);
        return "role/index";
    }

    @PostMapping("/tableSearch")
    @ResponseBody
    @AuthToken
    public ReturnVO tableSearch(@RequestBody RolesVo rolesVo) {
        ReturnVO returnVO = new ReturnVO();
        try {
            QueryWrapper<Roles> queryWrapper = new QueryWrapper<>();
            if (rolesVo.getRoleName() != null && !rolesVo.getRoleName().equals(""))
                queryWrapper.eq("roleName", rolesVo.getRoleName());
            if (rolesVo.getRoleID() > 0)
                queryWrapper.eq("roleID", rolesVo.getRoleID());
            else
                queryWrapper.ge("roleID", rolesVo.getCurrentRoleID());
            int total = rolesService.count(queryWrapper);

            if (rolesVo.getSort() != null && !rolesVo.getSort().equals("")) {
                if (rolesVo.getSortOrder().equals("desc"))
                    queryWrapper.orderByDesc(rolesVo.getSort());
                else
                    queryWrapper.orderByAsc(rolesVo.getSort());
            }

            List<Roles> list = new ArrayList<>();
            if (total > 0) {
                Page<Roles> page = new Page<>(rolesVo.pageIndex, rolesVo.pageSize);
                Page<Roles> rolesPage = rolesService.getBaseMapper().selectPage(page, queryWrapper);
                list = rolesPage.getRecords();
            }

            //得到当前菜单具备的功能权限
            List<Button> buttons = permissionService.filterPermission(String.valueOf(rolesVo.getCurrentRoleID()), menuId);
            list.forEach(model -> model.setButtonList(buttons));

            returnVO.setTotal(total);
            returnVO.setData(list);
            return returnVO;
        } catch (Exception e) {
            logger.error(e.getMessage());
            return new ReturnVO(ReturnCode.FAIL);
        }
    }

    /**
     * 查询大于等于当前角色
     *
     * @param roleID
     * @return
     */
    @GetMapping("/initRole")
    @ResponseBody
    @AuthToken
    public ReturnVO initRole(String roleID) {
        try {
            QueryWrapper<Roles> queryWrapper = new QueryWrapper<>();
            queryWrapper.ge("roleID", Integer.valueOf(roleID));
            List<Roles> list = rolesService.list(queryWrapper);
            return new ReturnVO(list);
        } catch (Exception e) {
            logger.error(e.getMessage());
            return new ReturnVO(ReturnCode.FAIL);
        }
    }

    @PostMapping("/del")
    @ResponseBody
    @AuthToken
    public ReturnVO del(@RequestBody Roles roles) {
        try {
            if (roles.getRoleCheckName() == null)
                rolesService.removeById(roles.getRoleID());
            else if (roles.getRoleCheckName().equals("superAdmin") || roles.getRoleCheckName().equals("admin") ||
                    roles.getRoleCheckName().equals("GeneralAgent") || roles.getRoleCheckName().equals("DistributionAgent"))
                return new ReturnVO(ReturnCode.VerificationFailed);
            else
                rolesService.removeById(roles.getRoleID());

            return new ReturnVO();
        } catch (Exception e) {
            logger.error(e.getMessage());
            return new ReturnVO(ReturnCode.FAIL);
        }
    }

    @PostMapping("/edit")
    @ResponseBody
    @AuthToken
    public ReturnVO edit(@RequestBody Roles roles) {
        try {
            rolesService.updateById(roles);
            return new ReturnVO();
        } catch (Exception e) {
            logger.error(e.getMessage());
            return new ReturnVO(ReturnCode.FAIL);
        }
    }

    @PostMapping("/add")
    @ResponseBody
    @AuthToken
    public ReturnVO add(@RequestBody Roles roles) {
        try {
            rolesService.save(roles);
            return new ReturnVO();
        } catch (Exception e) {
            logger.error(e.getMessage());
            return new ReturnVO(ReturnCode.FAIL);
        }
    }
}
